/*	$Id: signal.c 1111 2010-12-06 00:25:59Z phrakt $	*/
/*
 * Copyright (c) 2008 Jean-Francois Brousseau <phrakt@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>

#include <stdio.h>
#include <signal.h>
#include <string.h>

#include "log.h"
#include "signal.h"
#include "string.h"
#include "private.h"



/*
 * Getting a signal name is too system-independent, so we keep our own list
 * of well-known signal names and leave the rest in the dust.
 */
static const char* const sig_names[] = {
	"",
	"SIGHUP",
	"SIGINT",
	"SIGQUIT",
	"SIGILL",
	"SIGTRAP",
	"SIGABRT",
	"SIGEMT",
	"SIGFPE",
	"SIGKILL",
	"SIGBUS",
	"SIGSEGV",
	"SIGSYS",
	"SIGPIPE",
	"SIGALRM",
	"SIGTERM",
	"SIGURG",
	"SIGSTOP",
	"SIGTSTP",
	"SIGCONT",
	"SIGCHLD",
};






/*
 * We wrap calls to strsignal() with a mutex because the function is not
 * reentrant.
 */
static cnp_mutex_t   strsignal_mutex = CNP_MUTEX_INITIALIZER;


/*
 * cnp_sig_getname()
 *
 */
const char*
cnp_sig_getname(int signo)
{
	if ((signo >= (int)(sizeof(sig_names) / sizeof(sig_names[0]))) ||
	    (signo < 0)) {
		return (NULL);
	}

	return (sig_names[signo]);
}

/*
 * cnp_sig_getdesc()
 *
 */
const char*
cnp_sig_getdesc(int signo, char *buf, size_t len)
{
	char *sp;
	const char *ret = buf;

	if (cnp_mutex_lock(&strsignal_mutex) != 0) {
		cnp_log_err(cnp_logchan,
		    "failed to lock for strsignal() call");
		return (NULL);
	}

	if ((sp = strsignal(signo)) == NULL)
		ret = NULL;
	else
		strlcpy(buf, sp, len);

	(void)cnp_mutex_unlock(&strsignal_mutex);

	return (ret);
}
